<?php

class DefaultController extends BackController
{

    const NEWS_API = 'http://voithan.com/customer/api_news';

    public function setControllerMenu()
    {
        return array();
    }

    public function actionIndex()
    {
        if (Yii::app()->user->isGuest)
        {
            $this->redirect($this->createUrl('default/login', array('lang' => $this->lang)));
        }
        if (!$unserialize = Yii::app()->cache->get('customer_news'))
        {
            $serialize = @file_get_contents(self::NEWS_API);
            $unserialize = array();
            if ($serialize)
            {
                $unserialize = @unserialize($serialize);
            }
            Yii::app()->cache->set('customer_news', $unserialize, 300);
        }

        $this->render('index', array('customer_news' => $unserialize));
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if ($error = Yii::app()->errorHandler->error)
        {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionLogin()
    {
        $model = new AdminLoginForm;

// if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

// collect user input data
        if (isset($_POST['AdminLoginForm']))
        {
            $model->attributes = $_POST['AdminLoginForm'];
// validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect($this->createUrl('default/', array('lang' => $this->lang)));
        }
// display the login form
        $this->layout = "//layouts/login";
        $this->render('login', array('model' => $model));
    }

    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect($this->createUrl('default/login', array('lang' => $this->lang)));
    }

}